<!--
 * @Author: Craft
 * @Date: 2024-08-18
 * @Description: 暗黑破坏神2重置版BD分享列表
-->
<template>
  <view class="d2r-container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <u-search
        v-model="searchKeyword"
        placeholder="搜索BD名称或作者"
        :show-action="false"
        :clearabled="true"
        @search="handleSearch"
        @clear="handleClear"
        height="70rpx"
        bg-color="#0a0a0a"
        border-color="#333333"
        search-icon-color="#d4af37"
        color="#e0e0e0"
      ></u-search>
    </view>
    
    <!-- 职业筛选 -->
    <view class="class-filter">
      <scroll-view scroll-x="true" class="class-scroll" show-scrollbar="false">
        <view class="class-tabs">
          <view 
            class="class-tab" 
            :class="{ active: activeClass === classItem.value }" 
            v-for="classItem in classOptions" 
            :key="classItem.value"
            @click="setActiveClass(classItem.value)"
          >
            {{ classItem.label }}
          </view>
        </view>
      </scroll-view>
    </view>
    
    <!-- 排序选项 -->
    <view class="sort-bar">
      <view 
        class="sort-option" 
        :class="{ active: currentSort.field === 'createDate' }"
        @click="setSort({ field: 'createDate', order: 'desc', label: '最新' })"
      >
        最新
      </view>
      <view 
        class="sort-option" 
        :class="{ active: currentSort.field === 'viewCount' }"
        @click="setSort({ field: 'viewCount', order: 'desc', label: '热门' })"
      >
        热门
      </view>
      <view 
        class="sort-option" 
        :class="{ active: currentSort.field === 'favCount' }"
        @click="setSort({ field: 'favCount', order: 'desc', label: '收藏' })"
      >
        收藏
      </view>
    </view>
    
    <!-- BD列表 -->
    <view class="builds-container">
      <view v-if="loading" class="d2r-loading">
        <u-loading-icon mode="circle" color="#d4af37"></u-loading-icon>
        <text class="loading-text">加载中...</text>
      </view>
      
      <view v-else-if="filteredBuilds.length === 0" class="d2r-empty">
        <u-icon name="info-circle" size="48" color="#a0a0a0"></u-icon>
        <text class="empty-text">没有找到符合条件的BD</text>
      </view>
      
      <view v-else class="builds-list">
        <view 
          class="build-card" 
          v-for="build in filteredBuilds" 
          :key="build._id"
          @click="navigateToBuildDetail(build._id)"
        >
          <view class="build-header">
            <text class="build-title">{{ build.title }}</text>
            <view class="class-tag" :class="getClassTagClass(build.class)">{{ build.class }}</view>
          </view>
          
          <view class="build-content">
            <text class="build-desc">{{ getShortDescription(build.content) }}</text>
          </view>
          
          <view class="build-items" v-if="build.items && build.items.length > 0">
            <text class="items-title">核心装备:</text>
            <view class="items-list">
              <view class="item-icon" v-for="(itemId, index) in build.items.slice(0, 3)" :key="itemId">
                <image class="item-image" :src="getItemImage(itemId)" mode="aspectFit"></image>
              </view>
              <view class="item-more" v-if="build.items.length > 3">
                <text>+{{ build.items.length - 3 }}</text>
              </view>
            </view>
          </view>
          
          <view class="build-footer">
            <view class="build-author">
              <text>{{ build.author }}</text>
              <text class="build-date">{{ formatDate(build.createDate) }}</text>
            </view>
            <view class="build-stats">
              <view class="stat-item">
                <u-icon name="eye" size="14" color="#a0a0a0"></u-icon>
                <text class="stat-text">{{ build.viewCount }}</text>
              </view>
              <view class="stat-item">
                <u-icon name="star" size="14" color="#a0a0a0"></u-icon>
                <text class="stat-text">{{ build.favCount }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view v-if="hasMore && !loading" class="load-more" @click="loadMoreBuilds">
        <text>加载更多</text>
      </view>
    </view>
    
    <!-- 悬浮按钮 -->
    <view class="float-button" @click="showCreateBuildTip">
      <u-icon name="plus" color="#1a1a1a" size="24"></u-icon>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { loadData } from '@/common/d2r-data'

// 数据
const builds = ref([])
const filteredBuilds = ref([])
const items = ref({}) // 用于缓存装备信息
const loading = ref(true)
const hasMore = ref(false)
const pageSize = 10
const currentPage = ref(1)

// 搜索和筛选
const searchKeyword = ref('')
const activeClass = ref('all')
const currentSort = ref({ field: 'createDate', order: 'desc', label: '最新' })

// 职业选项
const classOptions = [
  { value: 'all', label: '全部' },
  { value: '亚马逊', label: '亚马逊' },
  { value: '野蛮人', label: '野蛮人' },
  { value: '死灵法师', label: '死灵法师' },
  { value: '圣骑士', label: '圣骑士' },
  { value: '法师', label: '法师' },
  { value: '德鲁伊', label: '德鲁伊' },
  { value: '刺客', label: '刺客' }
]

// 监听筛选条件变化
watch([searchKeyword, activeClass, currentSort], () => {
  currentPage.value = 1
  applyFilters()
}, { deep: true })

// 生命周期
onMounted(async () => {
  await Promise.all([
    loadBuildsData(),
    loadItemsData()
  ])
})

// 加载BD数据
async function loadBuildsData() {
  try {
    loading.value = true
    builds.value = await loadData('builds')
    applyFilters()
  } catch (error) {
    console.error('加载BD数据失败', error)
    uni.showToast({
      title: '加载BD数据失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 加载装备数据（用于显示BD中的装备图标）
async function loadItemsData() {
  try {
    const itemsList = await loadData('items')
    // 转换为对象，方便通过ID查找
    itemsList.forEach(item => {
      items.value[item._id] = item
    })
  } catch (error) {
    console.error('加载装备数据失败', error)
  }
}

// 应用筛选条件
function applyFilters() {
  let result = [...builds.value]
  
  // 搜索关键词
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(build => {
      // 搜索标题
      if (build.title.toLowerCase().includes(keyword)) {
        return true
      }
      
      // 搜索作者
      if (build.author.toLowerCase().includes(keyword)) {
        return true
      }
      
      // 搜索内容
      if (build.content && build.content.toLowerCase().includes(keyword)) {
        return true
      }
      
      return false
    })
  }
  
  // 职业筛选
  if (activeClass.value !== 'all') {
    result = result.filter(build => build.class === activeClass.value)
  }
  
  // 排序
  result.sort((a, b) => {
    const fieldA = a[currentSort.value.field] || 0
    const fieldB = b[currentSort.value.field] || 0
    
    if (currentSort.value.order === 'asc') {
      return fieldA > fieldB ? 1 : -1
    } else {
      return fieldA < fieldB ? 1 : -1
    }
  })
  
  // 分页
  const totalBuilds = result.length
  hasMore.value = totalBuilds > currentPage.value * pageSize
  
  filteredBuilds.value = result.slice(0, currentPage.value * pageSize)
}

// 加载更多
function loadMoreBuilds() {
  currentPage.value++
  applyFilters()
}

// 处理搜索
function handleSearch() {
  applyFilters()
}

// 清除搜索
function handleClear() {
  searchKeyword.value = ''
  applyFilters()
}

// 设置职业筛选
function setActiveClass(classValue) {
  activeClass.value = classValue
}

// 设置排序方式
function setSort(option) {
  currentSort.value = option
}

// 跳转到BD详情
function navigateToBuildDetail(buildId) {
  uni.navigateTo({
    url: `/pages-sub/builds/build-detail?id=${buildId}`
  })
}

// 显示创建BD提示
function showCreateBuildTip() {
  uni.showModal({
    title: '创建BD',
    content: '该功能将在后续版本中开放，敬请期待！',
    showCancel: false,
    confirmText: '我知道了'
  })
}

// 获取装备图片
function getItemImage(itemId) {
  if (items.value[itemId]) {
    return items.value[itemId].image || '/static/items/default.png'
  }
  return '/static/items/default.png'
}

// 获取内容简短描述
function getShortDescription(content) {
  if (!content) return ''
  return content.length > 80 ? content.substring(0, 80) + '...' : content
}

// 格式化日期
function formatDate(dateStr) {
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 获取职业标签样式类
function getClassTagClass(className) {
  switch (className) {
    case '亚马逊': return 'amazon'
    case '野蛮人': return 'barbarian'
    case '死灵法师': return 'necromancer'
    case '圣骑士': return 'paladin'
    case '法师': return 'sorceress'
    case '德鲁伊': return 'druid'
    case '刺客': return 'assassin'
    default: return ''
  }
}
</script>

<style lang="scss" scoped>
@import '../../common/d2r-theme.scss';
.d2r-container {
  min-height: 100vh;
  padding-bottom: 80px; // 为悬浮按钮留出空间
}

// 搜索栏
.search-bar {
  padding: 10px 15px;
  background-color: $d2r-bg-darker;
  position: sticky;
  top: 0;
  z-index: 10;
}

// 职业筛选
.class-filter {
  background-color: $d2r-bg-darker;
  padding-bottom: 10px;
  
  .class-scroll {
    width: 100%;
    white-space: nowrap;
    
    .class-tabs {
      display: inline-flex;
      padding: 0 15px;
      
      .class-tab {
        padding: 8px 15px;
        margin-right: 10px;
        font-size: 14px;
        color: $d2r-text-muted;
        position: relative;
        
        &.active {
          color: $d2r-gold;
          
          &::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 2px;
            background-color: $d2r-gold;
          }
        }
      }
    }
  }
}

// 排序选项
.sort-bar {
  display: flex;
  padding: 10px 15px;
  background-color: $d2r-bg-darker;
  border-bottom: 1px solid $d2r-border;
  
  .sort-option {
    padding: 5px 15px;
    font-size: 14px;
    color: $d2r-text-muted;
    position: relative;
    
    &.active {
      color: $d2r-gold;
      font-weight: bold;
    }
    
    &:not(:last-child)::after {
      content: '';
      position: absolute;
      right: 0;
      top: 25%;
      height: 50%;
      width: 1px;
      background-color: $d2r-border;
    }
  }
}

// BD列表
.builds-container {
  padding: 10px 15px;
  
  .builds-list {
    .build-card {
      background-color: $d2r-bg-darker;
      border-radius: 8px;
      padding: 15px;
      margin-bottom: 15px;
      
      .build-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        
        .build-title {
          font-size: 16px;
          color: $d2r-gold;
          font-weight: bold;
        }
      }
      
      .build-content {
        margin-bottom: 10px;
        
        .build-desc {
          font-size: 14px;
          color: $d2r-text;
          line-height: 1.4;
        }
      }
      
      .build-items {
        margin-bottom: 10px;
        
        .items-title {
          font-size: 12px;
          color: $d2r-text-muted;
          margin-bottom: 5px;
          display: block;
        }
        
        .items-list {
          display: flex;
          
          .item-icon {
            width: 40px;
            height: 40px;
            background-color: $d2r-bg-dark;
            border-radius: 4px;
            margin-right: 5px;
            padding: 2px;
            
            .item-image {
              width: 100%;
              height: 100%;
            }
          }
          
          .item-more {
            width: 40px;
            height: 40px;
            background-color: $d2r-bg-dark;
            border-radius: 4px;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 12px;
            color: $d2r-text-muted;
          }
        }
      }
      
      .build-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .build-author {
          font-size: 12px;
          color: $d2r-text;
          
          .build-date {
            margin-left: 10px;
            color: $d2r-text-muted;
          }
        }
        
        .build-stats {
          display: flex;
          
          .stat-item {
            display: flex;
            align-items: center;
            margin-left: 15px;
            
            .stat-text {
              font-size: 12px;
              color: $d2r-text-muted;
              margin-left: 4px;
            }
          }
        }
      }
    }
  }
  
  .load-more {
    text-align: center;
    padding: 15px 0;
    color: $d2r-gold;
    font-size: 14px;
  }
}

// 悬浮按钮
.float-button {
  position: fixed;
  right: 20px;
  bottom: 80px;
  width: 50px;
  height: 50px;
  border-radius: 25px;
  background-color: $d2r-gold;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  z-index: 100;
}
</style>